# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : process_view.py
# Time       ：2023/3/12 13:18
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    流程视图
    process views
"""
from datetime import datetime

from flask_restx import fields
from sqlalchemy import or_

from apis.orderlines import orderlines_ns
from apis.orderlines.models.process import Process
from apis.orderlines.schema.process_schema import ProcessSchema
from public.api_utils.api_decorator import handle_api_error
from public.base_export_excel_view import BaseExportExcelView
from public.base_response import MarshalModel
from public.base_view import BaseView, BaseDetailsView

process = {
    'process_id': fields.String(description='流程ID'),
    'process_name': fields.String(description='流程名称'),
    'version': fields.String(description='流程版本'),
    'version_desc': fields.String(description='版本描述'),
    'process_params': fields.Raw(description='流程运行实例参数'),
    'process_config': fields.Raw(description='流程运行实例流程'),
    'desc': fields.String(description='流程描述'),
    'mode': fields.String(description='流程运行方式'),
    'namespace': fields.String(description='流程的命名空间')
}
process_marshal = MarshalModel('process', orderlines_ns)


class ProcessDetailView(BaseDetailsView):
    url = '/process/detail'

    def __init__(self, *args, **kwargs):
        super(ProcessDetailView, self).__init__(*args, **kwargs)
        self.table_orm = Process
        self.table_schema = ProcessSchema

    @handle_api_error()
    @orderlines_ns.doc(description="获取流程配置详情")
    @orderlines_ns.expect(process_marshal.detail_request(process))
    @orderlines_ns.marshal_with(process_marshal.detail_response(process))
    def get(self):
        """获取流程配置详情"""
        return super(ProcessDetailView, self).get()


class ProcessView(BaseView):
    url = '/process'

    def __init__(self, *args, **kwargs):
        super(ProcessView, self).__init__(*args, **kwargs)
        self.table_orm = Process
        self.table_schema = ProcessSchema

    def handle_filter(self):
        self.filter.append(self.table_orm.active == 1)
        for key, val in self.form_data.items():
            if hasattr(self.table_orm, key) and val:
                self.filter.append(getattr(self.table_orm, key) == val)
            if key == 'keyword' and val:
                self.filter.append(or_(
                    self.table_orm.id == val,
                    self.table_orm.desc == val
                ))

    @handle_api_error()
    @orderlines_ns.doc(description='获取流程详情')
    @orderlines_ns.expect(process_marshal.list_request(process))
    @orderlines_ns.marshal_with(process_marshal.list_response(process))
    def get(self):
        """获取流程详情"""
        return super(ProcessView, self).get()

    @handle_api_error()
    @orderlines_ns.doc(description='创建流程')
    @orderlines_ns.expect(process_marshal.create_request(process))
    @orderlines_ns.marshal_with(process_marshal.create_response())
    def post(self):
        """创建流程"""
        return super(ProcessView, self).post()

    @handle_api_error()
    @orderlines_ns.doc(description='修改流程')
    @orderlines_ns.expect(process_marshal.update_request(process))
    @orderlines_ns.marshal_with(process_marshal.update_response())
    def put(self):
        """修改流程"""
        return super(ProcessView, self).put()

    @handle_api_error()
    @orderlines_ns.doc(description='删除流程')
    @orderlines_ns.expect(process_marshal.delete_request())
    @orderlines_ns.marshal_with(process_marshal.delete_response())
    def delete(self):
        """删除流程"""
        return super(ProcessView, self).delete()


class ProcessReportView(BaseExportExcelView):
    """
    流程导出
    http://127.0.0.1:15900/export/process
    """
    url = '/process/export'

    def __init__(self, *args, **kwargs):
        super(ProcessReportView, self).__init__(*args, **kwargs)
        self.file_name = f'process_{datetime.now().strftime("%Y-%m-%d")}'
        self.columns = {
            'id': '序号',
            'process_id': '流程id',
            'process_name': '流程名称',
            'process_params': '流程参数',
            'process_config': '流程配置',
            'insert_time': '创建时间',
            'update_time': '修改时间',
            'creator': '创建者',
            'updater': '修改者'
        }
        self.is_logger = True
        self.post_action = '导出流程报告'

    @handle_api_error()
    @orderlines_ns.doc(description='导出流程信息')
    @orderlines_ns.expect(process_marshal.list_request(process))
    def post(self):
        """导出流程信息"""
        return super(ProcessReportView, self).post()
